require_relative 'xml_helpers'

module CSDNConfig

	class PermissionRoles
		attr_reader :users

		include XMLHelpers

		Actions = %w{Run.Delete Item.Discover Item.Cancel Item.Workspace Item.Build Item.Read Item.Configure Item.Delete Run.Update}

		def initialize
			clear
		end

		def empty?
			@users.empty?
		end

		def emails
			@users.map(&:email)
		end

		def add(user, roles=:builder)
			add_user user
			add_permission user, roles
		end

		def add_user(*users)
			users.each do |user|
				_add_user _make_user(user)
			end
		end

		def add_permission(user, roles=:builder)
			_add_security(_make_user(user).name, roles)
		end

		def clear
			@roles = Hash.new{|h,k| h[k] = []}
			@users = []
			_add_security 'admin', :all # always include administrator
			_add_security 'USER', :reader
		end

		def _make_user user
			if user.respond_to?(:to_str)
				user = User.new(user.to_str)
			end

			user
		end

		def _add_user user
			@users << user
		end

		def _add_security(user, roles)
			roles = case roles
			when :all then Actions
			when :reader then %w{Item.Workspace Item.Read Run.Update}
			when :builder then %w{Item.Workspace Item.Build Item.Read Item.Configure Item.Delete}
			else
				roles
			end

			roles.each do |role|
				@roles[role] << user
			end
		end

		def security_xml
			apply_template <<SECURITY_TEMPLATE
    <hudson.security.AuthorizationMatrixProperty>
<% for role, roleUser in @roles do %>
<% for user in roleUser do %>
      <permission>hudson.model.<%= role %>:<%= user %></permission>
<% end %>
<% end %>
    </hudson.security.AuthorizationMatrixProperty>
SECURITY_TEMPLATE
		end
	end

end
